package com.google.code.linescount.actions;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;

import com.google.code.linescount.func.FileLines;
import com.google.code.linescount.func.MsgConsoleUtil;
import com.google.code.linescount.ui.CountDialog;

class CountJob extends Job{
	
	String dir;
	String pattern;
	Shell shell;
	int lines;
	public CountJob(String dir,String pattern) {
		super("CountJob");
		this.dir=dir;
		this.pattern=pattern;
	}
	
	public IStatus run(IProgressMonitor m) {
		lines= FileLines.getLines(new File(dir), pattern);
		return Status.OK_STATUS;
	}
}

public class LineCountAction implements IWorkbenchWindowActionDelegate {
	
	private IWorkbenchWindow window;

	public LineCountAction() {
		
	}

	public void run(IAction action) {
		
//		MessageConsoleStream console = MsgConsoleUtil.openLogConsole("Lines Count", 
//				"Information", 
//				"com.google.code.LinesCount"); 
//		console.println(new Date(System.currentTimeMillis()).toString());
		MsgConsoleUtil.printmsg(new Date(System.currentTimeMillis()).toString());
//		DirectoryDialog fd=new DirectoryDialog(window.getShell());
//		String path=fd.open();
//		int nums=FileLines.getLines(path);
		
		CountDialog cd=new CountDialog(window.getShell());
		cd.open();
		String pattern2=cd.getPattern();
		pattern2=pattern2.replaceAll("[.]","\\\\.");
		final String pattern=pattern2.replaceAll("[*]", ".*");
		try {
			MsgConsoleUtil.printmsg("The file extension pattern is: "+pattern);
		}
		catch(Exception e) {
			MsgConsoleUtil.printerr("ERROR: "+e.getMessage());
		}
		
		IWorkspace workspace=ResourcesPlugin.getWorkspace();
		IWorkspaceRoot root=workspace.getRoot();
		
		final String dirname=root.getLocation().toString();
		MsgConsoleUtil.printmsg("The root of workspace: "+dirname);
		IEditorInput editorInput=null;
		try {
			editorInput=window.getActivePage().getActiveEditor().getEditorInput();
		}
		catch(Exception e) {
			MsgConsoleUtil.printerr(e.getMessage());
		}
		if(editorInput instanceof IFileEditorInput) {
			try {
				IFile file=((IFileEditorInput)editorInput).getFile();
				IProject proj=file.getProject();
				MsgConsoleUtil.printmsg("File is "+file.getLocation().toString());
				MsgConsoleUtil.printmsg("Project is "+proj.getLocation().toString());
			}
			catch(Exception e) {
				MsgConsoleUtil.printerr(e.getMessage());
			}
		}
		//TODO: multi-thread?
//		Job job=new CountJob(dirname,pattern);
//		job.addJobChangeListener(
//				new JobChangeAdapter() {
//					public void done(IJobChangeEvent event) {
//						final boolean isSuccess=event.getResult().isOK();
//						window.getShell().getDisplay().asyncExec(
//								new Runnable() {
//									public void run() {
//										MessageDialog.openInformation(null, "Lines", "The are  lines code");	
//									}
//								}
//								);
//					}
//				}
//				);
//		job.schedule();
		final FileLines fl=new FileLines();
		try {
			ModalContext.run(new IRunnableWithProgress() {
				public void run(IProgressMonitor monitor)
						throws InvocationTargetException, InterruptedException {
					fl.lines=FileLines.getLines(new File(dirname), pattern);
					ModalContext.checkCanceled(monitor);
				}
			}, true, new NullProgressMonitor(), Display.getCurrent());
		} catch (InvocationTargetException e) {

		} catch (InterruptedException e) {
		}
//		int num=FileLines.getLines(new File(dirname),pattern);
		MessageDialog.openInformation(
				window.getShell(),
				"Lines",
				"The are "+fl.lines+" lines code"
				);
//		IProject projects[]=root.getProjects();
//		StringBuffer sb=new StringBuffer();
//		for(int i=0;i<projects.length;i++) {
//			console.println(projects[i].getName());
//			console.println(projects[i].getLocation().toString());
//			sb.append(projects[i].getName()+"\n");
//			sb.append(projects[i].getLocation()+"\n");
//		}
//		console.println(sb.toString());
		
	}

	/**
	 * Selection in the workbench has been changed. We 
	 * can change the state of the 'real' action here
	 * if we want, but this can only happen after 
	 * the delegate has been created.
	 * @see IWorkbenchWindowActionDelegate#selectionChanged
	 */
	public void selectionChanged(IAction action, ISelection selection) {
	}

	/**
	 * We can use this method to dispose of any system
	 * resources we previously allocated.
	 * @see IWorkbenchWindowActionDelegate#dispose
	 */
	public void dispose() {
	}

	/**
	 * We will cache window object in order to
	 * be able to provide parent shell for the message dialog.
	 * @see IWorkbenchWindowActionDelegate#init
	 */
	public void init(IWorkbenchWindow window) {
		this.window = window;
	}
	
	


}